from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth import authenticate, login
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.middleware.csrf import get_token

# class GetCSRFTokenView(APIView):
#     def get(self, request, *args, **kwargs):
#         token = get_token(request)  # 获取CSRF token
#         return Response({"csrfToken": token})

# # 在登陆接口添加csrf认证
# @method_decorator(csrf_protect, name='dispatch')
# class LoginView(APIView):
#     # 登陆不需要认证和权限
    
#     def post(self, request, *args, **kwargs):
#         # 获取前端传递的用户名和密码
#         username = request.data.get('username')
#         password = request.data.get('password')
        
#         # 验证用户名和密码
#         user = authenticate(request, username=username, password=password)
#         # 判断用户是否存在
#         if user is not None:
#             login(request, user)  # 登录用户
#             return Response({"message": "登录成功！"}, status=status.HTTP_200_OK)
#         else:
#             return Response({"message": "用户名或密码错误！"}, status=status.HTTP_401_UNAUTHORIZED)
 #==============================================================================================
# from rest_framework.authtoken.models import Token  # 导入Token模型，用于生成token       
# class TokenLoginView(APIView):
#     def post(self, request, *args, **kwargs):
#         # 获取前端传递的用户名和密码
#         username = request.data.get('username')
#         password = request.data.get('password')
        
#         user = authenticate(request, username=username, password=password)
#         if user:
#             # 生成token，每次登录都会生成一个新的token，之前的token会失效
#             token, created = Token.objects.get_or_create(user=user) 
#             return Response({"token": token.key}, status=status.HTTP_200_OK) 
#         else:
#             return Response({"message": "用户名或密码错误！"}, status=status.HTTP_401_UNAUTHORIZED)
 #===================================================================================================       

    